package com.jkgj.skykingkong.tms.infrastructure.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * @author Xuegui Yuan
 */
public class JsonUsernamePasswordAuthenticationFilter
    extends UsernamePasswordAuthenticationFilter {
  @Override
  public Authentication attemptAuthentication(HttpServletRequest request,
                                              HttpServletResponse response)
      throws AuthenticationException {

    if (!request.getMethod().equals("POST")) {//如果不是post访问,跑出异常,
      throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
    } else {
      ObjectMapper mapper = new ObjectMapper();
      Map result = null;
      try {
        result = mapper.readValue(request.getReader(), Map.class);
      } catch (IOException e) {
        throw new AuthenticationServiceException("Read JSON error");
      }
      String username = (String) result.get("username");
      String password = (String) result.get("password");
      if (username == null) {
        username = "";
      }

      if (password == null) {
        password = "";
      }
      username = username.trim();
      UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
      this.setDetails(request, authRequest);

      return this.getAuthenticationManager().authenticate(authRequest);
    }
  }
}
